package cn.edu.ntu.utils;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *
 * @author wpfc
 */
public final class JsonUtils {

	/**
	 * 构造函数私有化
	 */
	private JsonUtils() {
	}

	// 定义jackson对象
	private static ObjectMapper MAPPER = null;
	
	static{
		MAPPER = new ObjectMapper();
		MAPPER.setSerializationInclusion(Include.NON_NULL);  
	}

	/**
	 * 将对象转换成json字符串。
	 * 
	 * @param data
	 * @return
	 */
	public static String objectToJson(Object data) {
		try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将json结果集转化为对象
	 * 
	 * @param jsonData
	 *            json数据
	 * @param clazz
	 *            对象中的object类型
	 * @return
	 */
	public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
		try {
			T t = MAPPER.readValue(jsonData, beanType);
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将json数据转换成pojo对象list
	 * 
	 * @param jsonData
	 * @param beanType
	 * @return
	 */
	public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
		JavaType javaType = getCollectionType(ArrayList.class, beanType);
		try {
			List<T> list = MAPPER.readValue(jsonData, javaType);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/**   
	 * 获取泛型的Collection Type  
	 * @param collectionClass 泛型的Collection   
	 * @param elementClasses 元素类   
	 * @return JavaType Java类型   
	*/   
	private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
	    return MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
	}   

	public static String toJson(Object data) {
		return objectToJson(data);
	}
	public static <T> T toObject(String json, Class<T> clazz) {
		return jsonToPojo(json, clazz);
	}
	public static <T> List<T> toList(String json, Class<T> clazz) {
		return jsonToList(json, clazz);
	}

	public static void main(String[] args){
		String str = "[[],[\"59fadb05d3578010bc194371\",\"59fbe83ed357800f328d4096\",\"59fbe83fd357800ee7189561\"]]";
		List<Object> list = jsonToList(str,  Object.class);
		System.out.println("list size : " + list.size());
	}
	
}
